package com.cac.demo.controller.outStoreRoom;


import com.cac.demo.dao.materialReceive.PackageUnpackDao;
import com.cac.demo.dao.outBill.WmsInvOutBillHDao;
import com.cac.demo.service.CallInterface.CallInterfaceService;
import com.cac.demo.service.materialReceive.MaterialReceiptService;
import com.cac.demo.util.CreateCommonLog;
import com.cac.demo.util.PackageUnpackServiceUtil;
import com.cac.demo.util.adapter.ResponseMsg;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Objects;

@Slf4j
@Service
public class PackageUnpackService {
    @Autowired
    private PackageUnpackDao packageUnpackDao;
    @Autowired
    private CreateCommonLog createCommonLog;
    @Autowired
    private PackageUnpackServiceUtil packageUnpackServiceUtil;
    @Autowired
    private MaterialReceiptService materialReceiptService;
    @Autowired
    private CallInterfaceService callInterfaceService;
    @Autowired
    private WmsInvOutBillHDao wmsInvOutBillHDao;


    //查询缓存箱列表
    public List<HashMap> cacheList(String ip){
        return packageUnpackDao.cacheList(ip);
    }
    //查询工作包
    public PageInfo queryPackageTask(HashMap queryMap, int currentPage, int pageSize){
        PageHelper.startPage(currentPage,pageSize);
        List<HashMap> list = packageUnpackDao.queryPackageTask(queryMap);
        for(HashMap map : list){
            map.put("hasChildren",true);
        }
        PageInfo pageInfo = new PageInfo(list);
        return pageInfo;
    }

    public List<HashMap> queryAoByPackage(HashMap map){
        List<HashMap> list = packageUnpackDao.queryAoByPackage(map);
        for(HashMap data : list){
            List<HashMap> matchs = packageUnpackDao.queryMatchInfoByAo(data);
            if(matchs.size()>0){
                data.put("hasChildren",true);
                data.put("children",matchs);
            }
        }
        return list;
    }

    public ResponseMsg callUnpackPalletCode(List<HashMap> list, String ip){
        ResponseMsg responseMsg = new ResponseMsg();
        try{
            String msTaskPackageId = "";
            List<HashMap> matchs = this.getUnpackList(list);
            msTaskPackageId = (String)matchs.get(0).get("msTaskPackageId");
            List<String> palletCodes  = new ArrayList<>();

            for(HashMap match : matchs){
                if(Objects.isNull(match.get("workbinCode"))&&Objects.isNull(match.get("palletCode"))){
                    continue;
                }
                if(!Objects.isNull(match.get("workbinCode"))&& !palletCodes.contains(match.get("workbinCode"))){
                    palletCodes.add((String)match.get("workbinCode"));
                }
                if(!Objects.isNull(match.get("palletCode"))&& !palletCodes.contains(match.get("palletCode"))){
                    palletCodes.add((String)match.get("palletCode"));
                }
            }
            log.info("【拆包准备喊的箱子托盘集合】："+palletCodes);
            //创建任务
            for(String palletCode : palletCodes){
                HashMap gklog = new HashMap();
                createCommonLog.unpackOutbindTask(palletCode,ip,msTaskPackageId);
            }
            return responseMsg.setRetCode("200").setMessage("创建完毕");
        }catch (Exception e){
            e.printStackTrace();
            return responseMsg.setRetCode("201").setMessage("创建异常");
        }
    }

    public List<HashMap> getUnpackList(List<HashMap> list){
        List<HashMap> matchinfos = new ArrayList<>();//
        boolean flag = false;
        /***
         * 获取勾选工作包，AO，配套信息里面的配套信息，要去重
         * ***/
        for(HashMap map : list){
            if("package".equals(map.get("treeType"))){//前台传递的是工作包
                List<HashMap> pamatchList = packageUnpackDao.queryMatchInfoByPackageId(map);
                for(HashMap m : pamatchList){
                    for(HashMap info:matchinfos){
                        if(m.get("msAoMatchInfoId").equals(info.get("msAoMatchInfoId"))){
                            flag = true;
                            break;
                        }
                    }
                    if(!flag){
                        matchinfos.add(m);
                        flag = false;
                    }
                }
            }else if("ao".equals(map.get("treeType"))){//前台传递的是AO
                List<HashMap> matmps = packageUnpackDao.queryMatchInfoByAo(map);//查询AO下面所有的配套信息
                for(HashMap tmp : matmps){
                    for(HashMap m : matchinfos){
                        if(tmp.get("msAoMatchInfoId").equals(m.get("msAoMatchInfoId"))){
                            flag = true;
                            break;
                        }
                    }
                    if(!flag){//配套信息不在集合里面
                        matchinfos.add(tmp);
                        flag = false;
                    }
                }
            }else{//前台传递的是配套信息
                for(HashMap m : matchinfos){
                    if(m.get("msAoMatchInfoId").equals(map.equals("msAoMatchInfoId"))){
                        flag = true;
                        break;
                    }
                }
                if(!flag){
                    matchinfos.add(map);
                    flag = false;
                }
            }
        }
        return matchinfos;
    }

    public PageInfo queryPalletCodeMaterial(int currentPage, int pageSize, HashMap queryMap){
        String palletCode = queryMap.get("palletCode").toString();
        List<HashMap> list = new ArrayList<>();
        PageHelper.startPage(currentPage,pageSize);
        if(palletCode.startsWith("2")){
            list = packageUnpackDao.queryToolMaterial(palletCode);
        }else{
            list = packageUnpackDao.queryWorkbinMaterial(palletCode);
        }
        return new PageInfo(list);
    }

    @Transactional
    public ResponseMsg saveUnpackData(List<HashMap> unpackMatchinfos, String workbinCode, String toolCode, String userCode, String ip){
        ResponseMsg responseMsg = new ResponseMsg();
        for(HashMap unpackMatchinfo : unpackMatchinfos){
            if(!unpackMatchinfo.containsKey("unpackQty")||Integer.parseInt(unpackMatchinfo.get("unpackQty").toString())==0){
                continue;
            }
            unpackMatchinfo.put("workbinCode",workbinCode);
            unpackMatchinfo.put("toolCode",toolCode);
            //1:更新配套表
            packageUnpackDao.updateUnpackMatchInfo(unpackMatchinfo);
            //2：更新箱子表数量
            packageUnpackDao.updateWorkbinInfo(unpackMatchinfo);
            //3：更新托盘表数量
            packageUnpackDao.updateToolInfo(unpackMatchinfo);
            //4：更新台账占用信息
            packageUnpackDao.updateUnpackItemInventory(unpackMatchinfo);
            //5-1:插入占用表信息
            packageUnpackDao.insertUnpackAllotment(unpackMatchinfo);
            //5-2：更新原来的占用表信息状态
            packageUnpackDao.updateOutAllotment(unpackMatchinfo);
            //6:调用占用取消以及重新占用
            packageUnpackServiceUtil.unpackAllot2(unpackMatchinfo,userCode,ip);
        }
        responseMsg.setRetCode("200").setMessage("操作成功");
        return responseMsg;
    }

    public PageInfo querySendCancelData(HashMap map, int currentPage, int pageSize){
        PageHelper.startPage(currentPage,pageSize);
        return new PageInfo(packageUnpackDao.querySendCancelData(map));
    }
    public List<HashMap> queryAllotment(HashMap map){
        return packageUnpackDao.queryAllotment(map);
    }

    @Transactional
    public ResponseMsg cancelAlloment(HashMap map, String IP, String userCode){
        //更新占用表状态
        //撤销占用
        HashMap cancel = new HashMap();
        cancel.put("wmsInvOutAllotmentId",map.get("wmsInvOutAllotmentId").toString());
        cancel.put("opUserCode", userCode);
        if(IP==null||"".equals(IP)){
            IP = "172.17.53.59";
        }
        cancel.put("IP",IP);
        cancel.put("cancelQty",map.get("applyQty"));
        //拆包取消
        String canceldata=materialReceiptService.sortOccupyCancle(cancel);
        HashMap ret = callInterfaceService.sendBData("sendBData", "拆包取消", canceldata, "两网传输-发送业务数据");
        if("200".equals(ret.get("retCode"))){
            HashMap cMap = new HashMap();
            cMap.put("allotmentQty",map.get("applyQty"));
            cMap.put("wmsItemInventoryId",map.get("wmsItemInventoryId"));
            cMap.put("wmsInvOutAllotmentId",map.get("wmsInvOutAllotmentId"));
            //更新台账信息
            wmsInvOutBillHDao.updateItemInventoryCancel(cMap);
            //更新箱子表数据
            packageUnpackDao.updateWorkbinItemQty(cMap);
            //更新占用表状态
            packageUnpackDao.updateAllotmentStatus(map.get("wmsInvOutAllotmentId").toString());
            return new ResponseMsg().setRetCode("200").setMessage("取消占用成功");
        }else{
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return new ResponseMsg().setRetCode("201").setMessage("取消占用失败");
        }
    }
    /**
     * 分拣出库撤销
     * **/
    @Transactional
    public ResponseMsg cancelOut(HashMap map, String IP, String userCode){
        HashMap cancel = new HashMap();
        cancel.put("wmsInvOutAllotmentId",map.get("wmsInvOutAllotmentId").toString());
        //添加合格证号
        String mesCheckQualiticationId= null;
        if (map.get("mesCheckQualiticationId")!=null && map.get("mesCheckQualiticationId")!=""){
             mesCheckQualiticationId = String.valueOf(map.get("mesCheckQualiticationId"));
        }else{
             mesCheckQualiticationId= "";
        }
        cancel.put("HgzNo",mesCheckQualiticationId);
        cancel.put("opUserCode", userCode);
        if(IP==null||"".equals(IP)){
            IP = "172.17.53.59";
        }
        cancel.put("IP",IP);
        String canceldata=materialReceiptService.sortInvOutCancle(cancel);
        HashMap ret = callInterfaceService.sendBData("sendBData", "拆包取消", canceldata, "两网传输-发送业务数据");
        if("200".equals(ret.get("retCode"))){
            HashMap cMap = new HashMap();
            cMap.put("erpOutQty",map.get("applyQty"));
            cMap.put("wmsItemInventoryId",map.get("wmsItemInventoryId"));
            cMap.put("wmsInvOutAllotmentId",map.get("wmsInvOutAllotmentId"));
            //更新台账信息
            wmsInvOutBillHDao.updateInventory(cMap);
            //更新流水状态
            wmsInvOutBillHDao.erpOutOccupyCancel(cMap);
            return new ResponseMsg().setRetCode("200").setMessage("撤销出库成功");
        }else{
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return new ResponseMsg().setRetCode("201").setMessage("撤销出库失败");
        }
    }

    @Transactional
    public ResponseMsg clearAoMatchInfoSendData(HashMap map){
        //判断match_info表是否存在此数据
        int cnt = packageUnpackDao.queryMatchInfoIsClear(map);
        if(cnt==0){
            packageUnpackDao.updateDeliveryIsDeal(map);
            return new ResponseMsg().setMessage("此数据已处理，请确认").setRetCode("201");
        }
        //1:备份match_info表
        packageUnpackDao.addMatchInfoDel(map);
        //2：被workbin_material表
        packageUnpackDao.addWorkbinMaterialDel(map);
        //3:删除match_info表
        packageUnpackDao.deleteMatchInfo(map);
        //4：删除workbin_material表
        packageUnpackDao.deleteWorkbinMatch(map);
        //修改交接单表 is_deal为Y
        packageUnpackDao.updateDeliveryIsDeal(map);
        return new ResponseMsg().setMessage("处理完成").setRetCode("200");
    }

    public PageInfo querySortMaterial(HashMap page, HashMap queryMap){
        int pageNum = Integer.parseInt(page.get("currentPage").toString());
        int pageSize = Integer.parseInt(page.get("pageSize").toString());
        PageHelper.startPage(pageNum,pageSize);
        return new PageInfo(packageUnpackDao.querySortMaterial(queryMap));
    }

    @Transactional
    public ResponseMsg cancelSort(HashMap map, String IP, String userCode){
        //1:备份match_info表
        packageUnpackDao.addMatchInfoDel(map);
        //2：被workbin_material表
        packageUnpackDao.addWorkbinMaterialDel(map);
        //3:删除match_info表
        packageUnpackDao.deleteMatchInfo(map);
        //4：删除workbin_material表
        packageUnpackDao.deleteWorkbinMatch(map);
        //5:撤销占用
        //撤销占用
        HashMap cancel = new HashMap();
        cancel.put("wmsInvOutAllotmentId",map.get("wmsInvOutAllotmentId").toString());
        cancel.put("opUserCode", userCode);
        if(IP==null||"".equals(IP)){
            IP = "172.17.53.59";
        }
        cancel.put("IP",IP);
        cancel.put("cancelQty",map.get("packageCount"));
        //拆包取消
        String canceldata=materialReceiptService.sortOccupyCancle(cancel);
        HashMap ret = callInterfaceService.sendBData("sendBData", "拆包取消", canceldata, "两网传输-发送业务数据");
        if("200".equals(ret.get("retCode"))){
            HashMap cMap = new HashMap();
            cMap.put("allotmentQty",map.get("packageCount"));
            cMap.put("wmsItemInventoryId",map.get("wmsItemInventoryId"));
            cMap.put("wmsInvOutAllotmentId",map.get("wmsInvOutAllotmentId"));
            //更新台账信息
            wmsInvOutBillHDao.updateItemInventoryCancel(cMap);
            //更新箱子表数据
            packageUnpackDao.updateWorkbinItemQty(cMap);
            //更新占用表状态
            packageUnpackDao.updateAllotmentStatus(map.get("wmsInvOutAllotmentId").toString());
            return new ResponseMsg().setRetCode("200").setMessage("操作成功");
        }else{
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return new ResponseMsg().setRetCode("201").setMessage("操作失败").setErrorDesc("撤销占用失败");
        }
    }
}
